<template>
  <div class="pc-user">
    <div class="user-title">
      <a href="javascript:;" :class="{'active':ActiveIdx===0}" @click="changeActive(0)">个人信息</a>
      <a href="javascript:;" :class="{'active':ActiveIdx===1}" @click="changeActive(1)">账户安全</a>
    </div>
    <div class="user-content">
      <div class="update-box" v-show="ActiveIdx===0">
        <div class="update-info">
          <div class="update-item">
            <div class="left-label">头像</div>
            <div class="right-content">
              <div class="head-pic">
                <img :src="userInfo.Image">
              </div>
              <div class="upload-content">
                <p>图片大小不能超过4M</p>
                <van-uploader :before-read="checkImg" :after-read="onRead" :max-size="4194304">
                  <button class="upload-btn">上传头像</button>
                </van-uploader>
              </div>
            </div>
          </div>
          <div class="update-item">
            <div class="left-label">性别</div>
            <div class="right-content">
              <van-radio-group v-model="userInfo.Sex">
                <van-radio name="男">男</van-radio>
                <van-radio name="女">女</van-radio>
              </van-radio-group>
            </div>
          </div>
          <div class="update-item">
            <div class="left-label">昵称</div>
            <div class="right-content">
              <input
                :class="{'active':focusIdx==0}"
                @focus="onFocus(0)"
                @blur="onBlur"
                type="text"
                placeholder="请输入昵称"
                v-model="userInfo.NickName"
              >
            </div>
          </div>
          <div class="update-item">
            <div class="left-label">姓名</div>
            <div class="right-content">
              <input
                :class="{'active':focusIdx==1}"
                @focus="onFocus(1)"
                @blur="onBlur"
                type="text"
                placeholder="请输入姓名"
                v-model="userInfo.Name"
              >
            </div>
          </div>
          <div class="update-item">
            <div class="left-label">手机号</div>
            <div class="right-content">
              <input
                :class="{'active':focusIdx==2}"
                @focus="onFocus(2)"
                @blur="onBlur"
                type="text"
                placeholder="请输入手机号"
                v-model="userInfo.Phone"
              >
            </div>
          </div>
          <div class="update-item">
            <div class="left-label">公司</div>
            <div class="right-content">
              <input
                :class="{'active':focusIdx==3}"
                @focus="onFocus(3)"
                @blur="onBlur"
                type="text"
                placeholder="请输入公司"
                v-model="userInfo.Company"
              >
            </div>
          </div>
          <div class="update-item">
            <div class="left-label">职务</div>
            <div class="right-content">
              <input
                :class="{'active':focusIdx==4}"
                @focus="onFocus(4)"
                @blur="onBlur"
                type="text"
                placeholder="请输入职务"
                v-model="userInfo.Post"
              >
            </div>
          </div>
          <div class="update-item">
            <div class="left-label">邮箱</div>
            <div class="right-content">
              <input
                :class="{'active':focusIdx==5}"
                @focus="onFocus(5)"
                @blur="onBlur"
                type="text"
                placeholder="请输入邮箱"
                v-model="userInfo.Email"
              >
            </div>
          </div>
          <div class="update-item">
            <div class="left-label">地区</div>
            <div class="right-content">
              <el-cascader
                size="medium"
                :options="options"
                placeholder="请选择所在地区"
                separator
                v-model="selectedOptions"
                @change="addressChange"
              ></el-cascader>
            </div>
          </div>
        </div>
        <van-button class="save-btn" @click="UpdateUserInfo" size="normal">保存</van-button>
      </div>
      <div class="bind-box" v-show="ActiveIdx===1">
        <div class="bind-info">
          <div class="bind-content">
            <div class="bind-item">
              <div class="bind-item-label">绑定手机号</div>
              <div class="bind-item-value" v-if="isBindPhone">
                <span>{{mobile|HideMobile}}</span>
                <button @click="BindPhoneModel=true">更换</button>
              </div>
              <div class="bind-item-value" v-else>
                <span>未绑定，绑定手机号后可以使用手机号登录</span>
                <button @click="BindPhoneModel=true">去绑定</button>
              </div>
            </div>
            <div class="bind-item">
              <div class="bind-item-label">绑定微信号</div>
              <div class="bind-item-value" v-if="isBindWeixin">
                <span>已绑定</span>
                <button @click="UnbundingWeixin">解绑</button>
              </div>
              <div class="bind-item-value" v-else>
                <span>未绑定</span>
                <button @click="BindWeixin">去绑定</button>
              </div>
            </div>
            <div class="bind-item" v-if="isBindPhone">
              <div class="bind-item-label">登录密码</div>
              <div class="bind-item-value">
                <span>设置登录密码可以使用绑定的手机号登录</span>
                <button @click="toReset">去重置</button>
              </div>
            </div>
            <div class="bind-item">
              <div class="bind-item-label">注销账号</div>
              <div class="bind-item-value">
                <span>注销账号后将无法使用智慧展务平台提供的相关服务</span>
                <button @click="LogoutAccount">注销账号</button>
              </div>
            </div>
          </div>
          <van-popup v-model="BindPhoneModel">
            <div class="bind-mobile">
              <div class="model-title">绑定手机号</div>
              <div class="register-form">
                <div class="register-field">
                  <i class="field-icon field-icon-account"></i>
                  <input type="text" v-model.trim="Phone" maxlength="11" placeholder="请输入手机号">
                </div>
                <div class="register-field">
                  <i class="field-icon field-icon-img"></i>
                  <input type="text" v-model.trim="ImageVerifyCode" placeholder="请输入图形验证码">
                  <div class="image-code">
                    <img :src="CodeImageSrc" @click="getImageCode" alt="图形码">
                  </div>
                </div>
                <div class="register-field">
                  <i class="field-icon field-icon-phone"></i>
                  <input type="text" v-model.trim="VerifyCode" placeholder="请输入短信验证码">
                  <div class="code-btn">
                    <button :disabled="CodeBtnDisabled" @click="getVerifyCode">{{CodeBtnText}}</button>
                  </div>
                </div>
                <button class="bind-btn" @click="BindPhone">确定</button>
              </div>
            </div>
          </van-popup>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import $ from 'jquery';
import { Cascader } from 'element-ui';
import { regionData, CodeToText } from 'element-china-area-data';
export default {
  data() {
    return {
      ActiveIdx: 0,
      focusIdx: null,
      BindPhoneModel: false,
      options: regionData,
      selectedOptions: [],
      mobile: '',
      Phone: '',
      isBindPhone: false,
      isBindWeixin: false,
      ImageVerifyCode: '',
      CodeImageSrc: '',
      VerifyCode: '',
      ImageEncryptCode: '',
      CodeBtnDisabled: false,
      CodeBtnText: '获取验证码',
      userInfo: {
        Image: '',
        NickName: '',
        Phone: '',
        Name: '',
        Sex: '',
        Age: 0,
        Company: '',
        Post: '',
        Email: '',
        Province: '',
        City: '',
        District: ''
      }
    };
  },
  filters: {
    HideMobile(value) {
      return value.substring(0, 3) + '****' + value.substring(value.length - 4);
    }
  },
  created() {
    let token = this.$cookies.get('token');
    this.getLoginInfo(token);
  },
  components: {
    'el-cascader': Cascader
  },
  methods: {
    toReset() {
      if (this.isBindPhone) {
        window.location.href = '#/reset?phone=' + this.mobile;
      } else {
        this.$toast('您还未绑定手机号');
      }
    },
    LogoutAccount() {
      this.$dialog.confirm({
        title: '确认注销当前登录的账号？',
        message: '温馨提示：注销当前登录账号后您需要重新注册或使用微信重新授权登录才可以使用智慧展务平台相关服务'
      }).then(() => {
        var that = this;
        let token = this.$cookies.get('token');
        $.ajax({
          type: 'POST',
          url: that.baseUrl + '/api/account/DeleteUser',
          headers: { Authorization: token },
          success: function(res) {
            if (res.State) {
              that.$cookies.remove('token');
              localStorage.removeItem('token');
              window.location.href = '#/';
            }
          }
        });
      }).catch(() => {});
    },
    BindWeixin() {
      if (!this.isBindWeixin) {
        window.location.href = `http://es.11cm.com.cn/WeiXinManage/GetWeiXinOpenID?ST=test&NotRegister=true&ReferrerUrl=${encodeURIComponent(
          window.location.href
        )}`;
      }
    },
    UnbundingWeixin() {
      this.$dialog
        .confirm({
          title: '确定解绑当前微信号？'
        })
        .then(() => {
          var that = this;
          let token = this.$cookies.get('token');
          $.ajax({
            type: 'POST',
            url: that.baseUrl + '/api/account/UnbundleWeixin',
            headers: { Authorization: token },
            success: function(res) {
              if (res.State) {
                that.$toast.success('解绑成功！');
                that.isBindWeixin = false;
                localStorage.removeItem('Unionid');
              } else {
                that.$toast(res.Message);
              }
            }
          });
        })
        .catch(() => {});
    },
    BindPhone() {
      if (/^1[345678]\d{9}$/.test(this.Phone) == false) {
        this.$toast('请输入正确的手机号');
      } else if (this.VerifyCode == '') {
        this.$toast('请输入短信验证码');
      } else {
        var that = this;
        let token = this.$cookies.get('token');
        $.ajax({
          type: 'POST',
          url: that.baseUrl + '/api/account/BindingPhone',
          headers: { Authorization: token },
          data: {
            Phone: that.Phone,
            VerifyCode: that.VerifyCode
          },
          success: function(res) {
            if (res.State) {
              window.location.reload();
            } else {
              that.$toast(res.Message);
            }
          }
        });
      }
    },
    onFocus(index) {
      this.focusIdx = index;
    },
    onBlur() {
      this.focusIdx = null;
    },
    UpdateUserInfo() {
      var that = this;
      let token = this.$cookies.get('token');
      let infoObj = {
        Image: that.userInfo.Image,
        NickName: that.userInfo.NickName,
        Sex: that.userInfo.Sex,
        Company: that.userInfo.Company,
        Post: that.userInfo.Post,
        Email: that.userInfo.Email,
        Province: that.userInfo.Province,
        City: that.userInfo.City,
        District: that.userInfo.District
      };
      $.ajax({
        type: 'POST',
        url: `${that.baseUrl}/api/account/SubmitExtendInfo`,
        headers: { Authorization: token },
        data: JSON.stringify(infoObj),
        success: function(res) {
          if (res.State) {
            window.location.reload();
          } else {
            that.$toast(res.Message);
          }
        }
      });
    },
    checkImg(file) {
      if (file.size > 4194304) {
        this.$toast('图片大小不能超过4M，请重新上传');
        return false;
      } else {
        return true;
      }
    },
    onRead(file) {
      var that = this;
      if (file.file.size > 4194304) {
        var dataURL = file.content;
        var imaged = new Image();
        imaged.src = dataURL;
        imaged.onload = function() {
          var canvas = document.createElement('canvas');
          var ctx = canvas.getContext('2d');
          // 图片原始尺寸
          var originWidth = this.width;
          var originHeight = this.height;
          // 最大尺寸限制，可通过国设置宽高来实现图片压缩程度
          var maxWidth = 360,
            maxHeight = 360;
          // 目标尺寸
          var targetWidth = originWidth,
            targetHeight = originHeight;
          // 图片尺寸超过400x400的限制
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更宽，按照宽度限定尺寸
              targetWidth = maxWidth;
              targetHeight = Math.round(
                maxWidth * (originHeight / originWidth)
              );
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(
                maxHeight * (originWidth / originHeight)
              );
            }
          }
          // canvas对图片进行缩放
          canvas.width = targetWidth;
          canvas.height = targetHeight;
          // 清除画布
          ctx.clearRect(0, 0, targetWidth, targetHeight);
          // 图片压缩
          ctx.drawImage(imaged, 0, 0, targetWidth, targetHeight);
          dataURL = canvas.toDataURL('image/jpg', 0.5);
          that.userInfo.Image = dataURL;
        };
      } else {
        this.userInfo.Image = file.content;
      }
    },
    getLoginInfo(token) {
      var that = this;
      $.ajax({
        type: 'GET',
        url: that.baseUrl + '/api/account/get',
        headers: { Authorization: token },
        success: function(res) {
          if (res.State) {
            that.userInfo.Image = res.Image || '';
            that.userInfo.NickName = res.NickName || '';
            that.userInfo.Name = res.Name || '';
            that.userInfo.Phone = res.Phone || '';
            that.userInfo.Sex = res.Sex || '男';
            that.userInfo.Age = res.Age || 0;
            that.userInfo.Company = res.Company || '';
            that.userInfo.Post = res.Post || '';
            that.userInfo.Province = res.Province || '';
            that.userInfo.City = res.City || '';
            that.userInfo.District = res.District || '';
            if (res.Phone) {
              that.mobile = res.Phone;
              that.isBindPhone = true;
            }
            if (res.Unionid) {
              localStorage.setItem('Unionid', res.Unionid);
              that.$store.commit('SET_UNIONID', res.Unionid);
              that.isBindWeixin = true;
            }
            if (res.OpenID) {
              localStorage.setItem('OpenId', res.OpenID);
              that.$store.commit('SET_OPENID', res.OpenID);
            }
          } else {
            that.$toast(res.Message);
          }
        }
      });
    },
    getImageCode() {
      var that = this;
      $.ajax({
        type: 'GET',
        url: that.baseUrl + '/api/register/getImgVerifyCode',
        success: function(res) {
          if (res.State) {
            that.CodeImageSrc = res.ImageBase64;
            that.ImageEncryptCode = res.ImageEncryptCode;
          }
        }
      });
    },
    getVerifyCode() {
      if (this.Phone == '') {
        this.$toast('请先输入手机号');
      } else if (/^1[345678]\d{9}$/.test(this.Phone) == false) {
        this.$toast('手机号格式不正确');
      } else if (this.ImageVerifyCode == '') {
        this.$toast('请先输入图形验证码');
      } else {
        var that = this;
        this.CodeBtnDisabled = true;
        $.ajax({
          type: 'POST',
          url: that.baseUrl + '/api/register/getVerifyCode',
          data: {
            Phone: that.Phone,
            ImageEncryptCode: that.ImageEncryptCode,
            VerifyCode: that.ImageVerifyCode
          },
          success: function(res) {
            if (res.State) {
              let second = 120;
              that.CodeBtnText = '还剩' + second + '秒';
              var timer = setInterval(() => {
                second--;
                if (second > 0) {
                  that.CodeBtnText = '还剩' + second + '秒';
                } else {
                  clearInterval(timer);
                  that.CodeBtnDisabled = false;
                  that.CodeBtnText = '发送验证码';
                  second = 120;
                }
              }, 1000);
            } else {
              that.$toast(res.Message);
            }
          }
        });
      }
    },
    changeActive(index) {
      this.ActiveIdx = index;
    },
    addressChange(arr) {
      // console.log(CodeToText[arr[0]], CodeToText[arr[1]], CodeToText[arr[2]]);
      let Province = CodeToText[arr[0]];
      let City = CodeToText[arr[1]];
      if (
        Province.substr(Province.length - 1, 1) == '省' ||
        Province.substr(Province.length - 1, 1) == '市'
      ) {
        Province = Province.substring(0, Province.length - 1);
      }
      if (City.substr(City.length - 1, 1) == '市') {
        City = City.substring(0, City.length - 1);
      }
      this.userInfo.Province = Province;
      this.userInfo.City = City;
      this.userInfo.District = CodeToText[arr[2]];
    }
  },
  watch: {
    ActiveIdx: function(val, oldVal) {
      if (val === 1 && this.isBindPhone === false) {
        this.BindPhoneModel = true;
      }
    },
    BindPhoneModel: function(val, oldVal) {
      if (val) {
        this.getImageCode();
      }
    }
  }
};
</script>

<style>
.pc-media .pc-user {
  width: 60%;
  margin: 0 auto;
  min-height: 765px;
  box-sizing: border-box;
  padding: 30px;
}
.pc-user .user-title {
  width: 100%;
  border-bottom: 1px solid #ddd;
  display: flex;
}
.pc-user .user-title > a {
  display: inline-block;
  width: 120px;
  height: 50px;
  text-align: center;
  line-height: 40px;
  font-size: 18px;
  color: #4d4d4d;
}
.pc-user .user-title > a.active {
  border-bottom: 2px solid #00bcd4;
  color: #00bcd4;
}
.pc-user .update-info {
  margin: 20px 0 0 0;
  border-bottom: 1px solid #dcdfe6;
  padding: 0 0 20px 0;
}
.pc-user .upload-content > p {
  color: #999;
}
.pc-user .update-item {
  width: 100%;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  padding: 10px 0;
}
.pc-user .update-item > div {
  flex: 1;
}
.pc-user .left-label {
  max-width: 100px;
  font-size: 1em;
}
.pc-user .right-content {
  display: flex;
  align-items: center;
}
.pc-user .head-pic {
  width: 102px;
  height: 102px;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 30px 0 0;
}
.pc-user .upload-content {
  height: 102px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
}
.pc-user .upload-btn {
  width: 90px;
  height: 30px;
  background: #00bcd4;
  color: #fff;
  border-radius: 4px;
  line-height: normal;
}
.pc-user .van-radio-group {
  display: flex;
  justify-content: flex-end;
}
.pc-user .van-radio {
  margin: 0 20px 0 0;
}
.pc-user .van-radio__input {
  line-height: 1em;
}
.pc-user .van-radio .van-icon-checked {
  color: #37acff;
}
.pc-user .right-content > input {
  border: 1px solid #dcdfe6;
  height: 40px;
  line-height: 40px;
  border-radius: 4px;
  padding: 0 30px 0 15px;
  color: #606266;
}
.pc-user .right-content > input::placeholder {
  color: #dcdfe6;
}
.pc-user .right-content > input.active {
  border-color: #37acff;
}
.pc-user .el-cascader--medium {
  line-height: 40px;
}
.pc-user .save-btn {
  width: 200px;
  height: 40px;
  line-height: normal;
  border: 0;
  background: #37acff;
  color: #fff;
  margin: 20px 0 0 60px;
  border-radius: 4px;
}
.pc-user .bind-content {
  display: flex;
  flex-direction: column;
}
.pc-user .bind-item {
  display: flex;
  align-items: center;
  box-sizing: border-box;
  padding: 10px 0;
  line-height: 40px;
}
.pc-user .bind-item > div {
  flex: 1;
}
.pc-user .bind-item-label {
  max-width: 100px;
  font-size: 1em;
}
.pc-user .bind-item-value {
  display: flex;
}
.pc-user .bind-item-value > span {
  display: inline-block;
  white-space: nowrap;
  flex: 1;
  color: #999;
}
.pc-user .bind-item-value > button {
  width: 90px;
  height: 30px;
  background: #00bcd4;
  color: #fff;
  border-radius: 4px;
  line-height: normal;
  margin: 5px 0;
}
.pc-user .bind-mobile {
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
  width: 400px;
  padding: 20px 30px 10px 30px;
  background: #fff;
  border-radius: 4px;
}
.pc-user .model-title {
  margin: 0 0 20px 0;
  font-size: 1.2em;
}
.pc-user .bind-btn {
  width: 100%;
  height: 44px;
  background: #37acff;
  color: #fff;
  font-size: 1.125em;
  border-radius: 4px;
  margin: 10px 0;
}
</style>
